<template>
  <div class="app-container">
    <el-row class="mb5">
      <el-col :span="8">
        <el-tooltip class="box-item" content="开医嘱" effect="dark" placement="bottom">
          <el-button class="ml10" plain type="primary" @click="handleAddOrder">
            <template #icon>
              <i-ep-plus/>
            </template>
            开医嘱(F1)
          </el-button>
        </el-tooltip>
        <el-tooltip class="box-item" content="引用" effect="dark" placement="bottom">
          <el-button v-if="isQuoted" class="ml10" color="#8888ff" plain
                     @click="templateOpenOk">
            <svg-icon class="mr5" icon-class="template"/>
            引用
          </el-button>
        </el-tooltip>
        <el-tooltip v-if="!isQuoted" class="box-item" content="保存医嘱" effect="dark" placement="bottom">
          <el-button class="ml10" type="primary" @click="saveOrder">
            <svg-icon class="mr5" icon-class="save"/>
            保存医嘱(F8)
          </el-button>
        </el-tooltip>
        <el-tooltip class="box-item" content="刷新" effect="dark" placement="bottom">
          <el-button type="primary" @click="getList">
            <template #icon>
              <i-ep-search/>
            </template>
            刷新
          </el-button>
        </el-tooltip>
      </el-col>
      <el-col :span="16">
        <div style="float: right;margin-right: 25px">
        </div>
      </el-col>
    </el-row>
    <el-form ref="formRef" :model="form" :rules="rules">
      <el-table v-adaptive="500" :border="true" :data="form.orderList" :header-cell-style="$headerCellStyle"
                :stripe="true"
                highlight-current-row @selection-change="handleSelectionChange">
        <el-table-column :align="'center'" type="selection" width="40"/>
        <el-table-column v-if="isQuoted" :align="'center'" fixed="left" label="模板主题名称" prop="title" width="150">
          <template #default="scope">
            <span class="ys-css">{{ scope.row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column :align="'center'" class-name="small-padding fixed-width" fixed="right" label="操作"
                         width="50">
          <template #default="scope">
            <el-tooltip
              class="box-item" content="删除" effect="dark"
              placement="right">
              <el-button circle class="mb20" type="danger"
                         @click="handleDelete(scope.$index, scope.row)">
                <template #icon>
                  <i-ep-delete/>
                </template>
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column :align="'left'" fixed="left" label="组号" prop="groupNumber" width="110">
          <template #default="scope">
            <el-form-item v-show="scope.row.isShow"
                          :prop="'orderList.' + scope.$index + '.groupNumber'"
                          :rules="rules.groupNumber" class="table-form-margin">
              <el-input v-model="scope.row.groupNumber"
                        v-keyupEnter="{index: scope.$index, name: 'groupNumber' }"
                        :disabled="scope.row.groupNumberDisabled"
                        class="groupNumber"
                        clearable prop="groupNumber"
                        type="number"
                        @blur="groupNumberBlur($event, scope.$index, scope.row)"></el-input>
            </el-form-item>
            <span v-show="!scope.row.isShow">{{
                scope.row.groupNumber
              }}</span>
          </template>
        </el-table-column>
        <el-table-column :align="'left'" fixed="left" label="是否计价" prop="billingAttr" width="100">
          <template #default="scope">
            <el-form-item v-show="scope.row.isShow">
              <el-select v-model="scope.row.billingAttr"
                         v-keyupEnter="{index: scope.$index, name: 'billingAttr' }"
                         :disabled="scope.row.billingAttrDisabled"
                         class="width-120"
                         placeholder="请选择是否计价">
                <el-option v-for="dict in dictDataMap['billing_attr']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
            <span v-show="!scope.row.isShow"><dict-data-tag :options="dictDataMap['billing_attr']"
                                                            :value="scope.row.billingAttr"/></span>
          </template>
        </el-table-column>
        <el-table-column :align="'left'" fixed="left" label="医嘱类别" prop="orderClass" width="90">
          <template #default="scope">
            <el-form-item v-show="scope.row.isShow">
              <el-select v-model="scope.row.orderClass"
                         v-keyupEnter="{index: scope.$index, name: 'orderClass' }"
                         :disabled="scope.row.orderClassDisabled"
                         class="width-120"
                         placeholder="请选择医嘱类别"
                         @change="orderClassChange($event, scope.$index, scope.row,'1')">
                <el-option v-for="dict in dictDataMap['new_order_type']" :key="dict.dictValue"
                           :disabled="dict.dictValue ==='4'|| dict.dictValue ==='5'"
                           :label="dict.dictLabel" :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
            <span v-show="!scope.row.isShow"><dict-data-tag :options="dictDataMap['new_order_type']"
                                                            :value="scope.row.orderClass"/></span>
          </template>
        </el-table-column>
        <el-table-column :align="'left'" fixed="left" label="长/临" prop="repeatIncaditor" width="80">
          <template #default="scope">
            <el-form-item v-show="scope.row.isShow">
              <el-select v-model="scope.row.repeatIncaditor"
                         v-keyupEnter="{index: scope.$index, name: 'repeatIncaditor' }"
                         :disabled="scope.row.repeatIncaditorDisabled"
                         class="width-120"
                         placeholder="请选择长/临"
                         @change="repeatIncaditorChange($event, scope.$index, scope.row)">
                <el-option v-for="dict in dictDataMap['order_type']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
            <span v-show="!scope.row.isShow"><dict-data-tag :options="dictDataMap['order_type']"
                                                            :value="scope.row.repeatIncaditor"/></span>
          </template>
        </el-table-column>
        <el-table-column :align="'left'" :header-align="'center'" :show-overflow-tooltip="true" fixed="left"
                         label="医嘱内容"
                         prop="itemName">
          <template #default="scope">
            <template v-if="scope.row.isShow">
              <el-form-item :prop="'orderList.' + scope.$index + '.itemName'"
                            :rules="rules.itemName"
                            class="table-form-margin">
                                 <span
                                   v-if="scope.row.orderClass==='4' || scope.row.orderClass==='5'">
                                     {{ scope.row.itemName }}
                                 </span>
                <span v-else-if="scope.row.isShow && scope.row.orderClass==='3'">
                                    <el-input v-model="scope.row.itemName"/>
                                </span>
                <el-input v-else-if="scope.row.isShow && !scope.row.isAutoShow &&
                                (scope.row.orderClass==='1' || scope.row.orderClass==='2')"
                          v-model="scope.row.itemName"
                          @focus="isShowItemNameFocus(scope.$index, scope.row)"/>
                <automatic-completion v-else-if="scope.row.isAutoShow &&
                                (scope.row.orderClass==='1' || scope.row.orderClass==='2')"
                                      ref="itemAutomatic" :dict-array="dictArray"
                                      :table-body-list="tableBodyList"
                                      :table-head-list="tableHeadList" :title="itemTitle"
                                      :right-div-show-type="'westernMedicineByTemplate'" :width="950"
                                      style="width: 100%;"
                                      @itemNameInput="itemNameInput($event, scope.$index, scope.row)"
                                      @rowClick="rowClick($event, scope.$index, scope.row)"/>
              </el-form-item>
            </template>
            <template v-else>{{ scope.row.groupNumberStyle }}<span class="ml5">{{
                scope.row.itemName
              }}</span></template>
          </template>
        </el-table-column>
        <el-table-column :align="'left'" header-align="center" label="途径" prop="channel" width="100">
          <template #default="scope">
            <el-form-item v-show="scope.row.isShow"
                          :prop="'orderList.' + scope.$index + '.channel'"
                          :rules="rules.channel" class="table-form-margin">
              <administration-index v-keyupEnter="{index: scope.$index, name: 'channel' }"
                                    :disabled="scope.row.channelDisabled"
                                    :placeholder="'请选择途径'" :value="scope.row.channel"
                                    style="width: 100%"
                                    @administrationInfoChange="administrationInfoChange($event, scope.$index, scope.row)"/>
            </el-form-item>
            <span v-show="!scope.row.isShow">{{ scope.row.channelName }}
              <span v-if="scope.row.allergyResult"
                    :style="{color: scope.row.allergyResult!= '-' ?  '#ff0000' : '#159100',fontWeight:'bold'}"
                    class="ml5">({{
                  scope.row.allergyResult
                }})</span></span>
          </template>
        </el-table-column>
        <el-table-column :align="'center'" :show-overflow-tooltip="true" header-align="center" label="频次" prop="performFreq" width="100">
          <template #default="scope">
            <el-form-item v-show="scope.row.isShow"
                          :prop="'orderList.' + scope.$index + '.performFreq'"
                          :rules="rules.performFreq" class="table-form-margin">
              <perform-index ref="performIndex" v-keyupEnter="{index: scope.$index, name: 'performFreq' }"
                             :disabled="scope.row.performFreqDisabled"
                             :placeholder="'请选择频次'" :value="scope.row.performFreq"
                             style="width: 100%"
                             @performFreqInfoChange="performFreqInfoChange($event, scope.$index, scope.row)"/>
            </el-form-item>
            <span v-show="!scope.row.isShow">{{ scope.row.performFreqName }}</span>
          </template>
        </el-table-column>
        <el-table-column :align="'center'" label="执行时间" prop="nursePerformTime" width="120">
          <template #default="scope">
            <el-form-item v-show="scope.row.isShow"
                          :prop="'orderList.' + scope.$index + '.nursePerformTime'" class="table-form-margin">
              <el-input v-model="scope.row.nursePerformTime"
                        v-keyupEnter="{index: scope.$index, name: 'nursePerformTime' }"
                        :disabled="scope.row.nursePerformTimeDisabled"
                        class="input-mr"
                        clearable
                        @blur="nursePerformTimeBlur($event, scope.$index, scope.row)">
              </el-input>
            </el-form-item>
            <span v-show="!scope.row.isShow">{{ scope.row.nursePerformTime }}</span>
          </template>
        </el-table-column>
        <el-table-column :align="'center'" label="单次用量" prop="numSingle" width="100">
          <template #default="scope">
            <el-form-item v-show="scope.row.isShow"
                          :prop="'orderList.' + scope.$index + '.numSingle'"
                          :rules="rules.numSingle" class="table-form-margin">
              <el-input v-model="scope.row.numSingle"
                        v-keyupEnter="{index: scope.$index, name: 'numSingle' }"
                        :disabled="scope.row.numSingleDisabled"
                        class="input-mr"
                        clearable
                        @blur="inputBlur(scope.$index)">
                <template #append>{{ scope.row.minUnitsName }}</template>
              </el-input>
            </el-form-item>
            <span v-show="!scope.row.isShow"
                  style="margin-left: -15px"> {{ parseFloat(scope.row.numSingle).toFixed(2) }}<dict-data-tag
              :options="dictDataMap['spec_unit']" :value="scope.row.minUnits"
              style="margin: -23px -20px 0px 35px"/></span>
          </template>
        </el-table-column>
        <el-table-column :align="'center'" label="单次剂量" prop="singleDosage" width="100">
          <template #default="scope">
            <el-form-item v-show="scope.row.isShow"
                          :prop="'orderList.' + scope.$index + '.singleDosage'"
                          :rules="rules.singleDosage" class="table-form-margin">
              <el-input v-model="scope.row.singleDosage"
                        v-keyupEnter="{index: scope.$index, name: 'singleDosage' }"
                        :disabled="scope.row.singleDosageDisabled" class="input-mr" clearable
                        @blur="inputBlur(scope.$index)">
                <template #append>{{ scope.row.doseUnitsName }}</template>
              </el-input>
            </el-form-item>
            <span v-show="!scope.row.isShow"
                  style="margin-left: -15px"> {{ parseFloat(scope.row.singleDosage).toFixed(2) }}<dict-data-tag
              :options="dictDataMap['dose_unit']" :value="scope.row.doseUnits"
              style="margin: -23px -20px 0px 35px"/></span>
          </template>
        </el-table-column>
        <el-table-column :align="'center'" label="数量" prop="num" width="90">
          <template #default="scope">
            <el-form-item v-show="scope.row.isShow"
                          :prop="'orderList.' + scope.$index + '.num'"
                          :rules="rules.num" class="table-form-margin">
              <el-input v-model="scope.row.num" v-keyupEnter="{index: scope.$index, name: 'num' }"
                        :disabled="scope.row.sumNumDisabled"
                        class="input-mr"
                        clearable>
                <template #append>{{ scope.row.unitsName }}</template>
              </el-input>
            </el-form-item>
            <span v-show="!scope.row.isShow"
                  :style="!scope.row.packageUnits ?'margin-left: -14px':'margin-left: -15px'"> {{
                scope.row.num
              }}
              <!--                            {{ scope.row.unitsName }}-->
                                                        <dict-data-tag
                                                          v-if="scope.row.packageUnits"
                                                          :options="dictDataMap['spec_unit']" :value="scope.row.unit"
                                                          style="margin: -23px -20px 0px 35px"/>
                            </span>
          </template>
        </el-table-column>
        <el-table-column :align="'center'" label="首日是否摆药" prop="firstDayIsDisp" width="90">
          <template #default="scope">
            <el-form-item v-show="scope.row.isShow">
              <el-select v-model="scope.row.firstDayIsDisp"
                         v-keyupEnter="{index: scope.$index, name: 'firstDayIsDisp' }"
                         :disabled="scope.row.firstDayIsDispDisabled"
                         class="width-120"
                         placeholder="请选择首日是否摆药"
                         @change="firstDayIsDispChange($event, scope.$index, scope.row)">
                <el-option v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
            <span v-show="!scope.row.isShow"><dict-data-tag :options="dictDataMap['sys_yes_no']"
                                                            :value="scope.row.firstDayIsDisp"/></span>
          </template>
        </el-table-column>
        <el-table-column :align="'center'" label="首日摆药数量" prop="firstDayDrugDispAmount" width="100">
          <template #default="scope">
            <el-form-item v-show="scope.row.isShow"
                          :rules="rules.numSingle" class="table-form-margin">
              <el-input v-model="scope.row.firstDayDrugDispAmount"
                        v-keyupEnter="{index: scope.$index, name: 'firstDayDrugDispAmount' }"
                        :disabled="scope.row.firstDayDrugDispAmountDisabled"
                        class="input-mr"
                        clearable
                        @blur="inputBlur(scope.$index)">
                <template #append>{{ scope.row.minUnitsName }}</template>
              </el-input>
            </el-form-item>
            <span v-show="!scope.row.isShow" style="margin-left: -15px"> {{
                scope.row.firstDayDrugDispAmount
              }}<dict-data-tag
                :options="dictDataMap['spec_unit']" :value="scope.row.minUnits"
                style="margin: -23px -20px 0px 35px"/></span>
          </template>
        </el-table-column>
        <el-table-column :align="'center'" label="滴速" prop="dripSpeed" width="100">
          <template #default="scope">
            <el-form-item v-show="scope.row.isShow">
              <el-select v-model="scope.row.dripSpeed"
                         v-keyupEnter="{index: scope.$index, name: 'dripSpeed' }"
                         :disabled="scope.row.dripSpeedDisabled"
                         class="width-120"
                         clearable
                         placeholder="请选择滴速"
                         @change="dripSpeedChange($event, scope.$index, scope.row)">
                <el-option v-for="dict in dictDataMap['sys_drop_speed']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
            <span v-show="!scope.row.isShow"><dict-data-tag :options="dictDataMap['sys_drop_speed']"
                                                            :value="scope.row.dripSpeed"/></span>
          </template>
        </el-table-column>
        <el-table-column :align="'center'" label="医嘱说明" prop="remarks" width="120">
          <template #default="scope">
            <el-form-item v-show="scope.row.isShow"
                          :prop="'orderList.' + scope.$index + '.remarks'"
                          class="table-form-margin">
              <el-input v-model="scope.row.remarks" v-keyupEnter="{index: scope.$index, name: 'remarks' }"
                        :disabled="scope.row.remarksDisabled"
                        class="input-mr"
                        clearable>
              </el-input>
            </el-form-item>
            <span v-show="!scope.row.isShow">{{ scope.row.remarks }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <el-dialog
      v-model="dialogVisible"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :title="dialogTitle"
      :width="dialogWidth"
    >
    </el-dialog>
  </div>

</template>

<script lang="ts" setup>
import {listDept} from '@/api/system/dept'
import {autoPrescriptionList, autoPrescriptionListByTemplate} from "@/api/drug/drugStock.ts"
import {useDictStoreHook} from "@/store/modules/dict";
import {clinicTableHeadList, drugListByTemplate, jsonStrInObj, prescriptionList} from "@/utils/autoComplete"
import {getDrugVsDeptList} from "@/api/drug/drugStorageDept.ts"
import {autoBuildQuery} from "@/api/base/clinicItemDict.ts";
import {delTemplateDetail, insertBoByWholeSet, listTemplateDetail} from "@/api/patient/templateDetail.ts";
import {templateSubmitOkByOrderTemp} from "@/api/orders/orders.ts"

const {proxy} = getCurrentInstance() as any;


const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData('order_status', 'billing_attr', 'order_type', 'new_order_type',
  'sys_yes_no', 'spec_unit', 'sys_drop_speed', 'drug_classification', 'dose_unit'))

// 弹出框状态
const dialogVisible = ref<boolean>(false)
// 弹出框内容类别
const dialogType = ref<string>("")
//弹出框标题
const dialogTitle = ref<string>("")
// 弹出框宽度
const dialogWidth = ref<string>("40%")
// 项目选择自动补全窗体名称
const itemTitle = ref('选择项目')
// 项目选择自动补全表格表头
const tableHeadList = ref(jsonStrInObj(drugListByTemplate))
// 项目选择自动补全表格数据
const tableBodyList = ref([])
// 项目选择自动补全字典数组
const dictArray = ref(['bill_item_class_dict', 'is_medical_insurance'])
// 频次list
const performFreqList = ref<any>(dictStore.performFreqList)
const itemAutomatic = ref()
// 药房集合
const drugVsDeptList = ref<any>([])
const date = proxy.$parseTime(new Date(), "{y}-{m}-{d} ");
const dateRange = ref([date + "00:00:00", date + "23:59:59"]);
const formRef = ref()
const queryParams = ref<any>({
  repeatIncaditor: "",
})
const ids = ref([]);
const selectionThis = ref<any>([]);
const single = ref(true);
const multiple = ref(true);
const orderClass = ref("1")
const deptList = ref([])
const props = defineProps({
  orgId: {
    type: String,
    default: 0
  },
  templateMasterId: {
    type: String,
    default: ""
  },
  deptId: {
    type: String,
    default: ""
  },
  wardCode: {
    type: String,
    default: "",
  },
  storageId: {
    type: String,
    default: "",
  },
  // 是否从引用加载
  isQuoted: {
    type: Boolean,
    default: false
  }
})

const currentSelectDept = props.deptId

const autoForm = ref<any>({
  drugClassArray: [],
  // storageId: "",
  itemInfo: "",
  orgId: props.orgId
})

const form = ref<any>({
  // 医嘱
  orderList: []
})

/**
 * 校验方法中通过rule获取对应行的orderClass
 * @param obj
 */
function ruleToOrderClass(obj: any) {
  const strArray = obj.field.split(".")
  let index = 0;
  if (strArray.length > 1) {
    index = strArray[1]
  }
  return form.value.orderList[index].orderClass
}

/**
 * 组号校验规则
 * @param rule
 * @param value
 * @param callback
 */
const groupNumberValidator = (rule, value, callback) => {
  const orderClass = ruleToOrderClass(rule)
  if (orderClass === "1") {
    if (!value) {
      callback(new Error(rule.message || "组号不能为空"));
    }
    const pass = /^[0-9]\d*$/g.test(value);
    if (!pass) {
      callback(new Error(rule.message || "必须是正整数"));
    }
    callback();
  }
  callback();
}

/**
 * 频次选择框校验规则
 * @param rule
 * @param value
 * @param callback
 */
const performFreqValidator = (rule, value, callback) => {
  const orderClass = ruleToOrderClass(rule)
  if (orderClass === "1") {
    if (!value) {
      callback(new Error(rule.message || "频次不能为空"));
    }
    callback();
  }
  callback();
}

/**
 * 途径选择框校验规则
 * @param rule
 * @param value
 * @param callback
 */
const channelValidator = (rule, value, callback) => {
  const orderClass = ruleToOrderClass(rule)
  if (orderClass === "1") {
    if (!value) {
      callback(new Error(rule.message || "途径不能为空"));
    }
    callback();
  }
  callback();
}

/**
 * 单次用量校验规则
 * @param rule
 * @param value
 * @param callback
 */
const singleDoseValidator = (rule, value, callback) => {
  const orderClass = ruleToOrderClass(rule)
  if (orderClass === "1") {
    if (!value) {
      callback(new Error(rule.message || "单次用量不能为空"));
    }
    callback();
  }
  callback();
}

/**
 * 数量校验规则
 * @param rule
 * @param value
 * @param callback
 */
const sumNumValidator = (rule, value, callback) => {
  const orderClass = ruleToOrderClass(rule)
  if (orderClass === "1") {
    if (!value) {
      callback(new Error(rule.message || "数量不能为空"));
    }
    const pass = /^[0-9]\d*$/g.test(value);
    if (!pass) {
      callback(new Error(rule.message || "必须是正整数"));
    }
    callback();
  }
  callback();
}

/**
 * 医嘱内容校验规则
 * @param rule
 * @param value
 * @param callback
 */
const itemNameValidator = (rule, value, callback) => {
  if (!value) {
    callback(new Error(rule.message || "医嘱内容不能为空"));
  }
  callback();
}
// 表单校验
const rules = ref({
  groupNumber: [
    {validator: groupNumberValidator, trigger: "change"}
  ],
  num: [
    {validator: sumNumValidator, trigger: "change"}
  ],
  singleDosage: [
    {validator: singleDoseValidator, trigger: "change"}
  ],
  numSingle: [
    {validator: singleDoseValidator, message: "单次用量不能为空", trigger: "change"}
  ],
  itemName: [
    {validator: itemNameValidator, trigger: "change"}
  ],
  channel: [
    {validator: channelValidator, trigger: "change"}
  ],
  performFreq: [
    {validator: performFreqValidator, trigger: "change"}
  ],
})


function handleKeydown(event) {
  if (event.keyCode == "112") {
    // F1 新增医嘱
    //阻止浏览器默认事件
    event.preventDefault();
    handleAddOrder()
  } else if (event.keyCode == "113") {
    // F2 开检查
    //阻止浏览器默认事件
    event.preventDefault();
    handleAddExam()
  } else if (event.keyCode == "114") {
    // F3 开检验
    //阻止浏览器默认事件
    event.preventDefault();
    handleAddLab()
  } else if (event.keyCode == "115") {
    // F4 开中草药
    //阻止浏览器默认事件
    event.preventDefault();
  } else if (event.keyCode == "116") {
    // F6 手术申请
    //阻止浏览器默认事件
    event.preventDefault();
    handleAddOperating()
  }
}


/** 途径点击事件 */
function administrationInfoChange(event, index, row) {
  row.channel = toRaw(event).dictValue
  alikeGroupNumberFun(row, index)
}

/** 频次选择事件 */
function performFreqInfoChange(event, index, row) {
  const performFreqInfo = toRaw(event)
  row.performFreq = performFreqInfo.freqId
  row.performFreqInfo = performFreqInfo
  row.nursePerformTime = performFreqInfo.performTime
  alikeGroupNumberFun(row, index)
  // calculatedQuantityAndMoney(index)

}

/** 检查选择项目 */
function handleAddExam() {
  const orderListCount = form.value.orderList.length
  if (orderListCount > 0) {
    if (!form.value.orderList[orderListCount - 1].id) {
      return ElMessage.error("第" + orderListCount + "行数据还没有保存，请保存或者删除后再添加")
    }
  }
  dialogVisible.value = true
  dialogWidth.value = "40%"
  dialogType.value = "4"
}

/**
 * 医嘱保存
 */
function saveOrder() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      ElMessageBox.confirm("确认要保存开单吗", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let ordersTemplateList = form.value.orderList
        if (ordersTemplateList.length <= 0) {
          ElMessage.error("没有需要保存的医嘱。")
        }
        const data = {
          "detailBoList": ordersTemplateList,
          "orgId": props.orgId,
          "type": "2",
          "templateMasterId": props.templateMasterId,
        }
        insertBoByWholeSet(data).then(() => {
          ElMessage.success("医嘱明细保存成功")
          form.value.orderList = []
          getList()
        })
      }).catch(() => {
        ElMessage.info("取消操作");
      });
    }
  })
}


/** 检验选择项目 */
function handleAddLab() {
  const orderListCount = form.value.orderList.length
  if (orderListCount > 0) {
    if (!form.value.orderList[orderListCount - 1].id) {
      return ElMessage.error("第" + orderListCount + "行数据还没有保存，请保存或者删除后再添加")
    }
  }
  dialogVisible.value = true
  dialogWidth.value = "40%"
  dialogType.value = "5"
}

/**长/临 选择事件 */
function repeatIncaditorChange(event, index, row) {
  alikeGroupNumberFun(row, index)
  if (row.repeatIncaditor === "0") {
    row.firstDayIsDisp = "Y"
    calculatedQuantityAndMoney(index)
  } else {
    row.firstDayIsDisp = "N"
    row.firstDayDrugDispAmount = 0
  }
}


/* 执行时间 改变事件*/
function nursePerformTimeBlur(event, index, row) {
  alikeGroupNumberFun(row, index)
}

/* 下达时间 改变事件*/
function createTimeChange(event, index, row) {
  alikeGroupNumberFun(row, index)
}

/**
 * 组号改变事件
 */
function groupNumberBlur(_event, index: number, row: any) {
  if (form.value.orderList.length > 1) {
    // 获取当前行 行号
    const currentGroupNumber = row.groupNumber
    // 获取当前行的上一行数据
    const previousRow = form.value.orderList[index - 1]
    const previousGroupNumber = previousRow.groupNumber
    if (currentGroupNumber != null && currentGroupNumber == previousGroupNumber) {
      row.createTime = previousRow.createTime
      row.orderClass = previousRow.orderClass
      row.repeatIncaditor = previousRow.repeatIncaditor
      row.channel = previousRow.channel
      row.performFreq = previousRow.performFreq
      row.nursePerformTime = previousRow.nursePerformTime
      row.performFreqInfo = previousRow.performFreqInfo
    }
  }
}

/**首日是否摆药 选择事件 */
function firstDayIsDispChange(event, index, row) {
  if (row.firstDayIsDisp === "Y") {
    calculatedQuantityAndMoney(index)
  } else {
    row.firstDayDrugDispAmount = 0
  }
}

/**
 * 相同组号修改 事件
 */
function alikeGroupNumberFun(row: any, index: number) {
  // const groupNumber = row.groupNumber.replace(" ", "")
  const groupNumber = row.groupNumber
  if (groupNumber != "") {
    // 获取与当前行 组号相同的数据的下标 返回数组
    const alikeGroupNumberIndexArray = proxy.$getAllIndices(form.value.orderList, row.groupNumber, "groupNumber");
    alikeGroupNumberIndexArray.forEach((index: number) => {
      form.value.orderList[index].createTime = row.createTime
      form.value.orderList[index].orderClass = row.orderClass
      form.value.orderList[index].repeatIncaditor = row.repeatIncaditor
      form.value.orderList[index].channel = row.channel
      form.value.orderList[index].performFreq = row.performFreq
      form.value.orderList[index].nursePerformTime = row.nursePerformTime
      form.value.orderList[index].performFreqInfo = row.performFreqInfo
      calculatedQuantityAndMoney(index)
    })
  } else {
    // 组号为空
    calculatedQuantityAndMoney(index)
  }
}

/**
 * 新开医嘱类别事件
 * @param _event
 * @param index
 * @param row
 * @param type 1 列表点击 2 getList数据返回
 */
function orderClassChange(_event, index, row, type) {
  tableBodyList.value = []
  if (row.orderClass === "1") {
    if (!props.isQuoted) {
      tableHeadList.value = jsonStrInObj(drugListByTemplate)
    } else {
      tableHeadList.value = jsonStrInObj(prescriptionList)
    }
    //药品
    form.value.orderList[index].performFreqDisabled = false
    form.value.orderList[index].firstDayDrugDispAmountDisabled = false
    form.value.orderList[index].singleDoseDisabled = false
    form.value.orderList[index].singleDosageDisabled = false
    form.value.orderList[index].dripSpeedDisabled = false
    form.value.orderList[index].numSingleDisabled = false
    form.value.orderList[index].nursePerformTimeDisabled = false
    form.value.orderList[index].implementDeptDisabled = false
    form.value.orderList[index].remarksDisabled = false
    form.value.orderList[index].createTimeDisabled = false
    form.value.orderList[index].groupNumberDisabled = false
    form.value.orderList[index].repeatIncaditorDisabled = false
    form.value.orderList[index].isMedicalDisabled = false
    form.value.orderList[index].billingAttrDisabled = false
    form.value.orderList[index].performFreq = row.performFreq || ""
    form.value.orderList[index].channel = row.channel || ""
    form.value.orderList[index].singleDosage = row.singleDosage || ""
    form.value.orderList[index].numSingle = row.numSingle || ""
    form.value.orderList[index].num = row.num || "0"
    form.value.orderList[index].firstDayDrugDispAmount = row.firstDayDrugDispAmount || "0"
    form.value.orderList[index].billingAttr = "1"
  } else if (row.orderClass === "2") {
    tableHeadList.value = jsonStrInObj(clinicTableHeadList)
    //非药品
    form.value.orderList[index].performFreqDisabled = false
    form.value.orderList[index].firstDayDrugDispAmountDisabled = true
    form.value.orderList[index].singleDoseDisabled = true
    form.value.orderList[index].singleDosageDisabled = true
    form.value.orderList[index].dripSpeedDisabled = true
    form.value.orderList[index].numSingleDisabled = true
    form.value.orderList[index].nursePerformTimeDisabled = false
    form.value.orderList[index].implementDeptDisabled = false
    form.value.orderList[index].remarksDisabled = false
    form.value.orderList[index].createTimeDisabled = false
    form.value.orderList[index].groupNumberDisabled = true
    form.value.orderList[index].repeatIncaditorDisabled = false
    form.value.orderList[index].isMedicalDisabled = true
    form.value.orderList[index].billingAttrDisabled = false
    form.value.orderList[index].performFreq = row.performFreq || " "
    form.value.orderList[index].channel = row.channel || " "
    form.value.orderList[index].singleDosage = row.singleDosage || " "
    form.value.orderList[index].nursePerformTime = row.nursePerformTime || " "
    form.value.orderList[index].numSingle = row.numSingle || " "
    form.value.orderList[index].groupNumber = ""
    form.value.orderList[index].num = row.num || "1"
    form.value.orderList[index].firstDayDrugDispAmount = 0
    form.value.orderList[index].billingAttr = "1"
  } else if (row.orderClass === "3") {
    //嘱托
    form.value.orderList[index].performFreqDisabled = false
    form.value.orderList[index].firstDayDrugDispAmountDisabled = true
    form.value.orderList[index].channelDisabled = false
    form.value.orderList[index].singleDoseDisabled = true
    form.value.orderList[index].singleDosageDisabled = true
    form.value.orderList[index].dripSpeedDisabled = true
    form.value.orderList[index].numSingleDisabled = true
    form.value.orderList[index].nursePerformTimeDisabled = false
    form.value.orderList[index].implementDeptDisabled = false
    form.value.orderList[index].remarksDisabled = false
    form.value.orderList[index].createTimeDisabled = false
    form.value.orderList[index].groupNumberDisabled = true
    form.value.orderList[index].billingAttrDisabled = true
    form.value.orderList[index].repeatIncaditorDisabled = false
    form.value.orderList[index].isMedicalDisabled = true
    form.value.orderList[index].performFreq = row.performFreq || ""
    form.value.orderList[index].nursePerformTime = row.nursePerformTime || ""
    form.value.orderList[index].channel = row.channel || ""
    form.value.orderList[index].groupNumber = ""
    form.value.orderList[index].billingAttr = "2"
    form.value.orderList[index].firstDayDrugDispAmount = 0
  } else if (row.orderClass === "4") {
    //检查
    colDisabled(index, row)
  } else {
    // 检验
    colDisabled(index, row)
  }
  if (type === "1") {
    form.value.orderList[index].performFreq = undefined
    form.value.orderList[index].channel = undefined
    form.value.orderList[index].singleDosage = undefined
    form.value.orderList[index].numSingle = undefined
    form.value.orderList[index].num = undefined
    form.value.orderList[index].firstDayDrugDispAmount = undefined
    form.value.orderList[index].nursePerformTime = undefined
    form.value.orderList[index].remarks = undefined
    form.value.orderList[index].itemName = undefined
  }
}

/**
 * 医嘱列表禁用
 * @param index
 * @param row
 */
function colDisabled(index: number, row: any) {
  form.value.orderList[index].performFreqDisabled = true
  form.value.orderList[index].singleDoseDisabled = true
  form.value.orderList[index].singleDosageDisabled = true
  form.value.orderList[index].channelDisabled = true
  form.value.orderList[index].sumNumDisabled = true
  form.value.orderList[index].firstDayDrugDispAmountDisabled = true
  form.value.orderList[index].dripSpeedDisabled = true
  form.value.orderList[index].numSingleDisabled = true
  form.value.orderList[index].nursePerformTimeDisabled = true
  form.value.orderList[index].groupNumberDisabled = true
  form.value.orderList[index].implementDeptDisabled = true
  form.value.orderList[index].repeatIncaditorDisabled = true
  form.value.orderList[index].billingAttrDisabled = true
  form.value.orderList[index].remarksDisabled = true
  form.value.orderList[index].createTimeDisabled = true
  form.value.orderList[index].isMedicalDisabled = true
  form.value.orderList[index].performFreq = row.performFreq || " "
  form.value.orderList[index].singleDosage = row.singleDosage || ""
  form.value.orderList[index].nursePerformTime = row.nursePerformTime || ""
  form.value.orderList[index].numSingle = row.numSingle || ""
  form.value.orderList[index].billingAttr = "2"
}

/**
 * dialog关闭事件
 */
function handleClose() {
  dialogType.value = ""
  dialogVisible.value = false
}


/**
 * 滴速点击事件
 */
function dripSpeedChange(e, _index: number, row: any) {
  const sysDropSpeedArr: any = toRaw(dictDataMap.value['sys_drop_speed'])
  const indexNum = sysDropSpeedArr.findIndex((sysDropSpeed: any) => {
    return sysDropSpeed.dictValue === e
  })
  if (indexNum > -1) {
    if (row.remarks) {
      let str = row.remarks + "," + sysDropSpeedArr[indexNum].dictLabel
      row.remarks = str;
    } else {
      row.remarks = sysDropSpeedArr[indexNum].dictLabel
    }
  }
}


/**
 * 新增手术
 */
function handleAddOperating() {
  alert(1)
}

/**
 * 新增医嘱
 */
function handleAddOrder() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      // 最大的组号
      let maxGroupNumber = 0
      if (form.value.orderList.length > 0) {
        // 获取表格内最大的组号
        maxGroupNumber = Math.max.apply(Math, form.value.orderList.map((item: any) => {
          return item.groupNumber
        }))
      }
      // 重置医嘱类别
      orderClass.value = "1"
      form.value.orderList.push({
        detailId: "",
        orderClass: "1",
        billingAttr: "1",
        repeatIncaditor: "1",
        firstDayIsDisp: "N",
        isMedical: "Y",
        price: 0.00,
        groupNumber: maxGroupNumber + 1,
        itemName: "",
        num: "",
        firstDayDrugDispAmount: 0,
        numSingle: "",
        isShow: true,
        isAutoShow: false,
        createTime: proxy.$parseTime(new Date()),
        implementDept: currentSelectDept,
        // 途径是否禁用
        channelDisabled: false,
        // 频次是否禁用
        performFreqDisabled: false,
        // 单次用量是否禁用
        singleDoseDisabled: false,
        // 数量是否禁用
        sumNumDisabled: false,
        //首日摆药数量
        firstDayDrugDispAmountDisabled: false,
        // 滴速是否禁用
        dripSpeedDisabled: false,
        // 单次用量是否禁用
        numSingleDisabled: false,
        // 护士执行时间是否禁用
        nursePerformTimeDisabled: false,
        // 组号是否禁用
        groupNumberDisabled: false,
        // 下达时间是否禁用
        createTimeDisabled: false,
        // 医生说明是否禁用
        remarksDisabled: false,
        // 是否计价是否禁用
        billingAttrDisabled: false,
        // 长/临是否禁用
        repeatIncaditorDisabled: false
      })
      nextTick(() => {
        initInputDOM(form.value.orderList.length - 1);
      });
    }
  })
}

function initInputDOM(index) {
  //获取id为table-form下的所有input 框
  const inputDoms = document.querySelectorAll(
    ".groupNumber .el-input__inner"
  )
  inputDoms[index].focus();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  selectionThis.value = selection
  ids.value = selection.map(item => item.detailId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 删除 */
function handleDelete(index: number, row: any) {
  ElMessageBox.confirm('删除后数据将会丢失，确定要继续操作吗？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    if (!props.isQuoted) {
      if (!row.detailId) {
        form.value.orderList.splice(Number(index), 1)
        ElMessage.success("删除成功")
      } else {
        const idsThis = row.detailId || ids.value;
        delTemplateDetail(idsThis).then(() => {
          form.value.orderList.splice(Number(index), 1)
          ElMessage.success("删除成功")
        })
      }
    } else {
      form.value.orderList.splice(index, 1)
      ElMessage.success("删除成功")
    }
  })
}

/**
 * 自动补全上边input获得焦点事件
 * @param _index
 * @param row
 */
function isShowItemNameFocus(_index: number, row: any) {
  row.isAutoShow = true
  nextTick(() => {
    itemAutomatic.value.init()
    itemAutomatic.value.setItemName(row.itemName)
    itemAutomatic.value.focusInput()
  })
}

/** 项目名称自动补全检索 */
function itemNameInput(event: any, _index, row) {
  autoForm.value.itemInfo = event
  if (row.orderClass === "1") {
    if (!props.isQuoted) {
      tableHeadList.value = jsonStrInObj(drugListByTemplate)
    } else {
      tableHeadList.value = jsonStrInObj(prescriptionList)
    }
    getListDrugItem(row)
  } else if (row.orderClass === "2") {
    tableHeadList.value = jsonStrInObj(clinicTableHeadList)
    getListClinicItemDict()
  }

}

/** 自动补全后台查询非药品 */
function getListClinicItemDict() {
  if (autoForm.value.itemInfo) {
    autoForm.value.notInSelect = ['A', 'B', 'C', 'D', 'F', 'J', 'K', 'L']
    // 是否过滤已存在的项目标记
    autoForm.value.isFiltrationContrastExist = true
    autoBuildQuery(autoForm.value).then(res => {
      tableBodyList.value = res.data
      // 打开自动补全弹出框
      itemAutomatic.value.init()
    })
  } else {
    tableBodyList.value = []
  }
}

/** 自动补全后台查询药品 */
function getListDrugItem(row) {
  if (autoForm.value.itemInfo) {
    autoForm.value.orgId = props.orgId
    if (!props.isQuoted) {
      autoForm.value.storageId = ""
      autoPrescriptionListByTemplate(autoForm.value).then(res => {
        let data = res.data
        // 打开自动补全弹出框
        itemAutomatic.value.init()
        if (row.repeatIncaditor === '0') {
          // 长期
          tableBodyList.value = data.filter(item => item.packSize === "1" || item.packageNum === 1)
        } else {
          //临时
          tableBodyList.value = data
        }
      })
    } else {
      autoForm.value.storageId = props.storageId
      autoPrescriptionList(autoForm.value).then(res => {
        let data = res.data
        // 打开自动补全弹出框
        itemAutomatic.value.init()
        if (row.repeatIncaditor === '0') {
          // 长期
          tableBodyList.value = data.filter(item => item.packSize === "1" || item.packageNum === 1)
        } else {
          //临时
          tableBodyList.value = data
        }
      })
    }
  } else {
    tableBodyList.value = []
  }
}

/** 项目列表行点击事件 */
function rowClick(e: any, index: number, row: any) {
  itemAutomatic.value.setItemName(e.itemName)
  itemAutomatic.value.closePopover()
  row.isShow = true
  row.isAutoShow = false
  row.doseUnits = e.doseUnits
  row.singleDosage = e.dose
  row.singleDosageMin = e.dose
  let drugClass = ""
  if (e.drugClass === "1" || e.drugClass === "2") {
    drugClass = "A"
  } else {
    drugClass = "B"
  }
  row.itemClass = e.itemClass || drugClass
  row.doseUnitsName = e.doseUnitsName
  if (!row.channel) {
    row.channel = e.channel
  }
  if (!row.performFreq) {
    row.performFreq = e.performFreq
    row.performFreqInfo = dictStore.getAppointPerformFreqInfo(e.performFreq)
    row.nursePerformTime = dictStore.getAppointPerformFreqInfo(e.performFreq).performTime
  }
  row.packageSpec = e.packageSpec || e.itemSpec
  row.clinicItemId = e.drugPriceId || e.clinicItemId
  row.identicalInfoId = e.identicalInfoId
  row.minUnits = e.minUnits
  row.minUnitsName = e.minUnitsName
  row.minSpec = e.minSpec
  row.packageUnits = e.packageUnits
  row.packSize = e.packSize
  row.singleUnit = e.doseUnits
  row.unitsName = e.unitsName
  // 发药药房
  // row.storageId = e.storageId
  row.packageNum = e.packageNum
  row.packageNumCalculate = e.packSize === "1" ? 1 : e.packageNum || 1
  row.drugInfoId = e.drugInfoId
  row.itemName = e.drugName || e.itemName
  row.price = e.price || e.subTotal
  row.quantityAndUnits = e.quantityAndUnits
  row.orgId = e.orgId
  // row.implementDept = e.storageId
  row.sort = index + 1
  inputBlur(index)
  tableBodyList.value = []
}

/**
 * 单次剂量input失去焦点事件
 */
function inputBlur(index: number) {
  calculatedQuantityAndMoney(index)
}


/**
 * 计算数量 和金额
 */
function calculatedQuantityAndMoney(index: number) {
  const orderClassThis = form.value.orderList[index].orderClass
  // 最小剂量
  const singleDosageMin = form.value.orderList[index].singleDosageMin
  // 单次剂量（不用做计算）
  const singleDosage = form.value.orderList[index].singleDosage
  // 单次用量 实际开出剂量
  let numSingle = 0
  // 包装数量
  let packageNumCalculate = 1
  // 医嘱类别药品、非药品、嘱托  1: 药品
  if (orderClassThis === "1") {
    numSingle = form.value.orderList[index].numSingle || 1
    packageNumCalculate = form.value.orderList[index].packageNum
  } else {
    numSingle = 1
    packageNumCalculate = 1
  }
  if (typeof numSingle !== "undefined" && typeof packageNumCalculate !== "undefined") {
    let performTime: number = 1;
    // 获取频次对应的服用次数
    if (toRaw(form.value.orderList[index].performFreqInfo) !== undefined && toRaw(form.value.orderList[index].performFreqInfo).performTime !== undefined) {
      performTime = form.value.orderList[index].performFreqInfo ?
        form.value.orderList[index].performFreqInfo.performTime.split("-").length : 1
    }
    // 计算实际开出的单次用量和最小剂量的商
    // const num: number = Number(Math.ceil(singleDosage / singleDosageMin))
    const num: number = Number(numSingle)
    const amount: number = Number(Math.ceil(performTime * num))
    // 计算实际开出的单次用量和最小剂量的商
    const packSize = form.value.orderList[index].packSize
    // 列表中总数量
    let sumNum: number = 0
    if (packSize === "1") {
      // 小包装
      sumNum = amount
    } else {
      // 大包装
      sumNum = Number(Math.ceil(amount / packageNumCalculate))
    }
    // 给总数量赋值
    form.value.orderList[index].num = sumNum
    if (form.value.orderList[index].repeatIncaditor === '0') {
      //首日摆药数量
      form.value.orderList[index].firstDayDrugDispAmount = amount
    } else {
      //首日摆药数量
      form.value.orderList[index].firstDayDrugDispAmount = 0
    }
  }
}


// 以科室id查询对应的药房、药库信息
function getDrugVsDeptListFun() {
  let data = {
    deptId: currentSelectDept,
    orgId: props.orgId,
    clinicOrVisitArray: proxy.$stringToArray("1,2", ","),
    storageTypeArray: proxy.$stringToArray("3,4", ","),
    drugGrantTypeArray: proxy.$stringToArray("2", ","),
    storageClassArray: proxy.$stringToArray("2,3", ","),
  }
  getDrugVsDeptList(data).then((res: any) => {
    if (!res.data) {
      return ElMessage.error("本科室未绑定摆药药房，无法开药品医嘱，请联系药房人员添加后再开药。")
    }
    drugVsDeptList.value = res.data
    prescriptionTypeChange()
  })
}


function prescriptionTypeChange() {
  // 西药
  autoForm.value.drugClass = "A"
  autoForm.value.storageId = drugVsDeptList.value[0].id
  autoForm.value.prescAttr = "1"
  autoForm.value.drugClassArray = drugVsDeptList.value[0].drugClass.split(",")
}

function handleQuery() {
  getList()
}

function getList() {
  const param = {
    orgId: props.orgId,
    type: '2',
    itemName: queryParams.value.itemName,
    repeatIncaditor: queryParams.value.repeatIncaditor,
  }
  form.value.orderList = []
  listTemplateDetail(proxy.$addDateRange(param, dateRange.value)).then((res: resType) => {
    let unSave = form.value.orderList.filter(e => e.id == null)
    form.value.orderList = []
    const data: any = res.data
    data.forEach((item: any, index) => {
      item.itemId = ""
      item.isShow = !item.itemName.includes("中草药");
      // 设置药品或者非药品显示自动补全组件
      item.isAutoShow = !(item.orderClass === '1' || item.orderClass === '2');

      // 设置免皮试 如果是不能编辑状态 noSkin 设置为 true或者false，用于多选按钮选中，否则设置为 Y或者N，用于字典显示
      // item.noSkin = trDisabled.value === true ? item.noSkin === "Y" : item.noSkin
      item.doseUnitsName = dictStore.getMateDictInfo(dictDataMap.value['dose_unit'], item.doseUnits).dictLabel
      const unit = item.packSize === "1" ? item.minUnits : item.packageUnits
      item.unit = unit
      item.unitsName = dictStore.getMateDictInfo(dictDataMap.value['spec_unit'], unit).dictLabel
      item.minUnitsName = dictStore.getMateDictInfo(dictDataMap.value['spec_unit'], item.minUnits).dictLabel
      item.orderClassDisabled = item.orderClass === '4' || item.orderClass === '5'
      let price: number = 0;
      if (item.ordersCostVoList != null) {
        item.ordersCostVoList.forEach(orderCost => {
          price += Number(orderCost.price)
        })
      }
      item.price = price
      form.value.orderList.push(item)
      orderClassChange(null, index, item, '2')
    })
    form.value.orderList = form.value.orderList.concat(unSave)
    unSave = []
  })
}

// 获取科室集合
function getDeptList() {
  let queryParams = {
    orgId: props.orgId
  }
  listDept(queryParams).then(res => {
    deptList.value = res.data
  })
}

/**
 * 模板引用
 */
const emits = defineEmits(['historyCancel']);

function templateOpenOk() {
  if (selectionThis.value.length <= 0) {
    return ElMessage.error("请选择需要引用的模板数据后再操作。")
  }
  console.log("selectionThis.value", selectionThis.value)
  ElMessageBox.confirm("是否确认使用模板？", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    selectionThis.value.forEach((item: any) => {
      item.doseUnits = item.singleUnit
      item.createTime = proxy.$parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}")
      item.firstDayIsDisp = !item.firstDayIsDisp ? "N" : item.firstDayIsDisp
      item.isMedical = "Y"
      item.orderStatus = "1"
      item.orderText = item.itemName
      item.packageNumCalculate = item.packSize === "1" ? 1 : item.packageNum
      item.patientId = proxy.$patientId
      item.visitId = proxy.$visitId
      item.sumNum = item.num
      item.storageId = props.storageId
      item.implementDept = proxy.$currentSelectDept
    })
    const data = {
      ordersList: selectionThis.value,
      orgId: props.orgId,
      patientId: proxy.$patientId,
      visitId: proxy.$visitId,
      storageId: props.storageId
    }
    templateSubmitOkByOrderTemp(data).then(() => {
      emits('historyCancel')
      ElMessage.success("保存成功");
    });
  })
}

getDeptList()
// getDrugVsDeptListFun()
getList()

defineExpose({
  getList
})

</script>

<style lang="scss" scoped>
:deep(.el-input-group__append) {
  padding: 0 5px;
  width: 40px;
}

:deep(.el-input__wrapper .el-input__inner) {
  margin-right: -15px;
}

:deep(.el-form-item__content) {
  margin-bottom: 6px;
}

:deep(.el-form-item__error) {
  font-size: 11px;
  color: #ff0000;
}

:deep(.el-button--small) {
  --el-button-size: 20px;
}

:deep(.el-table__body tr.current-row>td>div>button>span ) {
  color: #000000 !important;
}


</style>
